package com.pan.service;

import com.pan.constants.DatabaseInfo;
import com.pan.dao.User;
import com.pan.dao.UserDAO;
import com.pan.dao.UserDAOImpl;
import com.pan.util.CheckAuth;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/removefile")
public class RemoveFile extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding(StandardCharsets.UTF_8.name());

        String token = request.getParameter("token");
        if (!CheckAuth.checkToken(token)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        UserDAO userDAO = UserDAOImpl.getInstance();
        User user = userDAO.getUserByToken(token);
        String filePath = DatabaseInfo.FILE_PATH + "\\" + user.getFilePath() + "\\";

        String path = request.getParameter("path");
        if (path != null) {
            path = java.net.URLDecoder.decode(path, "UTF-8");
            filePath = filePath + path;
        }

        String fileName = request.getParameter("fileName");
        if (fileName != null) {
            fileName = java.net.URLDecoder.decode(fileName, "UTF-8");
        }

        String fullPath = filePath + "\\" + fileName;

        File fileToDelete = new File(fullPath);
        if (fileToDelete.exists()) {
            if (fileToDelete.delete()) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to delete file.");
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
        }
    }
}
